<template>
  <el-table
    ref="myTable"
    :data="tableData"
    border
    stripe
    class="formula_table_content"
  >
    <el-table-column
      v-for="col in columns"
      :prop="col.key"
      :key="col.key"
      :label="col.key"
      :render-header="renderHeader"
    >
      <template slot-scope="scope">
        <el-input
          placeholder="请输入"
          v-model="scope.row[col.key]"
          size="mini"
          clearable
          v-if="!col.additional.length"
        ></el-input>
      </template>
    </el-table-column>
    <el-table-column label="操作" align="center" width="auto">
      <template slot="header">
        <div class="flex-x">
          <!-- <div style="margin-right: 10px">操作</div> -->
          <el-button type="primary" size="small" @click="addFormula"
            >添加</el-button
          >
        </div>
      </template>
      <template slot-scope="scope">
        <el-button type="danger" size="mini" @click="del(scope.$index)"
          >删除</el-button
        >
      </template>
    </el-table-column>
  </el-table>
</template>

<script>
export default {
  props: {
    columns: {
      type: Array,
      default: () => []
    },
    tableData: {
      type: Array,
      default: () => []
    }
  },
  mounted() {},
  methods: {
    // 删除
    del(index) {
      this.tableData.splice(index, 1);
      this.$emit("del", index);
    },
    // 生成当前行数据
    renderTableRow() {
      let obj = {};
      this.columns.forEach(item => {
        if (!obj[item.kye]) {
          obj[item.key] = "";
        }
      });
      return {
        ...obj
      };
    },

    // 操作 添加
    addFormula() {
      this.tableData.push(this.renderTableRow());
      this.$nextTick(() => {
        // myTable是表格的ref属性值
        if (this.$refs.myTable && this.$refs.myTable.doLayout) {
          this.$refs.myTable.doLayout();
        }
      });
      console.log("this.tableData :>> ", this.tableData);
    },
    // 表头部重新渲染
    renderHeader(h, { column, $index }) {
      // 新建一个 span
      let span = document.createElement("span");
      // 设置表头名称
      span.innerText = column.label;
      // 临时插入 document
      document.body.appendChild(span);
      // 重点：获取 span 最小宽度，设置当前列，注意这里加了 20，字段较多时还是有挤压，且渲染后的 div 内左右 padding 都是 10，所以 +20 。（可能还有边距/边框等值，需要根据实际情况加上）
      // column.minWidth = span.getBoundingClientRect().width + 20;
      column.width = "auto";
      // 移除 document 中临时的 span
      document.body.removeChild(span);
      return h("span", column.label);
    }
  }
};
</script>

<style lang="scss" scoped>
.formula_table_content {
  /deep/ {
    .el-table__header {
      width: 100%;
    }
    .el-table th.gutter {
      display: table-cell !important;
    }
    .el-table__body {
      width: 100%;
      .cell {
        padding: 0 6px !important;
      }
    }
  }
}
</style>
